package com.hzlh.log;
 
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.hzlh.core.utils.StringUtils;
import com.hzlh.domain.po.LoginAdmin;
import com.hzlh.domain.po.PermissionsPo;
import com.hzlh.domain.po.UserOperLogPo;
import com.hzlh.service.LogService;
import com.hzlh.service.RolePermService;
import com.hzlh.shiro.ShiroUser;

@Aspect
@Component
public class SystemLogAspect {
	
	//本地异常日志记录对象
    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect. class);
    private static final String ACTION = ".ACTION";
    private static final String PATH = ".PATH";
    //读取配置
    private static PropertiesConfiguration config = null;
    //注入Service用于把日志保存数据库
	@Autowired
    private LogService logService;
	@Autowired
	private RolePermService rolePermService;
	
	public SystemLogAspect() {
		try {
			config = new PropertiesConfiguration("methodlog-CN.properties");
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
	}
	
    @Pointcut("@annotation(com.hzlh.log.MethodLog)")
    public void logAspect() {
    }
     
    @Before("logAspect()")
    public void doBefore(JoinPoint joinPoint) {
    	HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();  
    	Subject subject = SecurityUtils.getSubject();
		ShiroUser shiroUser = (ShiroUser)subject.getPrincipal();
		if(shiroUser != null){
			LoginAdmin loginUser = shiroUser.getUser();
	        //请求的IP
	        String ip = getIpAddr(request);
	         try {
//	          System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
//	          System.out.println("方法描述:" + getControllerMethodDescription(joinPoint));
//	          System.out.println("请求人:" + loginUser.getUserId());
//	          System.out.println("请求IP:" + ip);
	            String url = request.getRequestURL().toString();
	            String param = request.getQueryString();
	            String type = request.getMethod();
//	            PermissionsPo permissionsPo = getControllerMethodPermissions(joinPoint);]
	            String[] Logs = getControllerMethodDescription(joinPoint);
	            UserOperLogPo logPo = new UserOperLogPo();
	            logPo.setUserId(loginUser.getId());
	            logPo.setUserName(loginUser.getUserId());
	            logPo.setOper(Logs[0]);
	            logPo.setPath(Logs[1]);
	            logPo.setIp(ip);
	            logPo.setUrl(url);
	            logPo.setParam(param);
	            logPo.setType(type.toLowerCase());
	            //保存数据库
	            logService.save(logPo);
	        }  catch (Exception e) {
	            //记录本地异常日志
	            logger.error("异常信息:{}", e.getMessage());
	        }
		}
    }
     
    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
     public static String[] getControllerMethodDescription(JoinPoint joinPoint)  throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String[] logs = new String[2];
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
               Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length && config != null) {
               	 MethodLog log = method.getAnnotation(MethodLog.class);
               	 String key = log.key();
//               logs[0] = log.description();
//               logs[1] = log.path();
               	 logs[0] = config.getString(key + ACTION);
               	 logs[1] = config.getString(key + PATH);
                 break;
               }
           }
       }
        return logs;
    }
     
     public PermissionsPo getControllerMethodPermissions(JoinPoint joinPoint)  throws Exception {
         String targetName = joinPoint.getTarget().getClass().getName();
         String methodName = joinPoint.getSignature().getName();
         Object[] arguments = joinPoint.getArgs();
         Class targetClass = Class.forName(targetName);
         Method[] methods = targetClass.getMethods();
         String key = "";
         for (Method method : methods) {
             if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                 if (clazzs.length == arguments.length) {
               	  String[] result = method.getAnnotation(RequiresPermissions.class).value();
                    if(result.length > 1){
                    	//获取当前值
//                    	key = result[index];
                    }else if(result.length == 1){
                    	key = result[0];
                    }
                    //获取方法上的所有注解
//               	Annotation[] annotations = method.getAnnotations();
//               	for(Annotation annotation : annotations){
//               	    System.out.println(annotation);
//               	}
                    break;
                 }
             }
         }
         if(StringUtils.isNotBlank(key)){
        	List<PermissionsPo> list = rolePermService.getPermAuthorizName(key);
        	if(list.size() > 0){
        		return list.get(0);
        	}
         }
         return null;
     }
     
     public static String getIpAddr(HttpServletRequest request) {
    	 String ip = request.getHeader("X-Forwarded-For");
	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	    	 ip = request.getHeader("Proxy-Client-IP");
	     }
	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	         ip = request.getHeader("WL-Proxy-Client-IP");
	     }
	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	    	 ip = request.getHeader("HTTP_CLIENT_IP");
	     }
	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	    	 ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	     }
	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	    	 ip = request.getRemoteAddr();  
	         //这里主要是获取本机的ip,可有可无  
	         if (ip.equals("127.0.0.1") || ip.endsWith("0:0:0:0:0:0:1")) {
	        	 // 根据网卡取本机配置的IP  
	       	     InetAddress inet = null;  
	       	     try {
	       	    	 inet = InetAddress.getLocalHost();  
	       	     } catch (UnknownHostException e) {  
	       	         e.printStackTrace();  
	       	     }  
	       	     ip = inet.getHostAddress();  
	       	 }
	     }
	     // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
	     return ip!=null && !"".equals(ip) ? ip.split(",")[0]:null;
	}
     
     public static void main(String[] args) {
    	 PropertiesConfiguration config = null; 
    	 try { 
	         config = new PropertiesConfiguration("methodlog-CN.properties"); 
	         System.out.println(config.getString("BANNER.SET.PATH"));
	     } catch (Exception e) { 
	         e.printStackTrace();
	     } 

	}

}